package com.iscas.green.databasechaostest.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 1. 创建自定义 Servlet
@WebServlet(name = "myServlet", urlPatterns = "/my-servlet")
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("text/plain;charset=UTF-8");
            response.getWriter().write("Hello from MyServlet");
        } catch (Exception e) {
            try {
                // 重要：不要抛出ServletException或IOException
                // 设置响应状态码为200，避免触发容器的默认错误页面
                response.setStatus(HttpServletResponse.SC_OK);
                response.setContentType("text/plain;charset=UTF-8");
                response.getWriter().write("发生错误: " + e.getMessage());
                // 打印堆栈信息到日志
                e.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}